package edu.ynu.se.xiecheng.achitectureclass.project.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class VideoTokenService {
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e";
    private static final String TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";

    /**
     * 获取视频 Token
     */
    public Map<String, Object> getVideoToken() {
        try {
            // 直接从服务器获取 Token 数据
            return fetchNewToken();
        } catch (Exception e) {
            // 构建标准的Spring Boot错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("timestamp", new Date());
            errorResponse.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorResponse.put("error", "Internal Server Error");
            errorResponse.put("path", "/api/token/video");

            return errorResponse;
        }
    }

    /**
     * 从萤石云获取新的 Token
     */
    private Map<String, Object> fetchNewToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", ACCOUNT_ID);

        // 直接返回从服务器获取的完整响应
        return restTemplate.postForObject(TOKEN_URL, requestBody, Map.class);
    }
}